﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BulldogCMS.Core.Storage;
using BulldogCMS.Core.Runtime.Modules;
using BulldogCMS.Core.Runtime;
using System.Globalization;
using BulldogCMS.Core.Storage.DataTypes.MVC;

namespace BulldogCMS.Core.MVC
{
    public class RewritingModule: IHttpModule
    {


        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.LocalPath.Contains(".")) return;

            Context.Application.RequestContextProvider.SetRequestContext(new RequestContext());

            string firstSegment =                       GetFirstSegmentName(HttpContext.Current.Request.Url.Segments);
            IModuleAreaProvider moduleAreaProvider =    GetModuleAreaProvider(firstSegment);
            
            if (moduleAreaProvider != null)
            {
                Context.Request.CurrentModuleAreaProvider = moduleAreaProvider;
            }
            else
            {
                Site currentSite = null;
                Node currentNode = Context.Application.URLResolver.GetNodeByURL(HttpContext.Current.Request, out currentSite);
                Context.Request.CurrentNode = currentNode;
                Context.Request.CurrentSite = currentSite;
                Context.Request.Language = CultureInfo.GetCultureInfo(Context.Request.CurrentSite.Language);

                var version = currentNode.GetValue<MVCPresentation>("MVCPresentation");

                if (version != null)
                {
                    Context.Request.CurrentActionName =     version.ActionName;
                    Context.Request.CurrentAreaName =       version.AreaName;
                    Context.Request.CurrentControllerName = version.ControllerName;
                    Context.Request.CurrentViewName =       version.ViewName;
                    Context.Request.CurrentLayoutName =     version.LayoutName;

                    if (Context.Request.CurrentAreaName != null)
                    {
                        HttpContext.Current.RewritePath(string.Format("~/withArea/{0}/{1}/{2}/{3}","1","2", Context.Request.CurrentActionName,"4"));
                    }
                    else
                    {
                        HttpContext.Current.RewritePath(string.Format("~/withoutArea/{0}/{1}/{2}", "1", Context.Request.CurrentActionName, "3"));
                    }
                }

                // TODO přesměrování na správné hodnoty z nastavení
                
            }
        }

        private IModuleAreaProvider GetModuleAreaProvider(string firstSegmentName)
        {
            var moduleAreaProvider = (from p in Context.Application.AreaProviders
                                      where p.AreaName.Equals(firstSegmentName, StringComparison.InvariantCultureIgnoreCase)
                                      select p).FirstOrDefault();
            return moduleAreaProvider;
        }

        private string GetFirstSegmentName(string[] segments)
        {
            foreach (string segment in segments)
            {
                if (segment != null && !string.IsNullOrEmpty(segment.Trim('/')))
                {
                    return segment.Trim('/');
                }
            }
            return "/";
        }

    }
}